<!--
*@Author: QWP
*@Description: 公共的人员选择弹窗
*@Date 2024-09-09 15:19
-->
<template>
  <UDialog
    :title="$attrs['title'] || '人员选择'"
    v-bind="$attrs"
    wrap-class-name="full-modal"
    destroyOnClose
    @submit="submit"
    @close="dialogClose">
    <Layout class="f-h-100">
      <CollapsedSider
        width="350px"
        :canExpand="false">
        <Collapse
          v-model:activeKey="activeKey"
          ghost
          class="u-role-user-collapse">
          <CollapsePanel
            v-for="(item, index) in treeData"
            :key="index + ''">
            <template #header>
              {{checkedKeys['c'+index]}}
              <CheckboxGroup v-model:value="parentCheckes['parent'+index]"
                :name="'parent'+index"
                :options="[{label: item.name, value: item.keyid}]"
                @change="(e) => parentChange(e, item, index)"
                @click="checkedClick">
              </CheckboxGroup>
            </template>
            <template #extra></template>
            <Tree
              :treeData="item['children'] || []"
              :checkable="multiple"
              :fieldNames="{
                title: 'name',
                key: 'keyid',
                children: 'children',
              }"
              v-bind="treeProps"
              v-model:expandedKeys="treeEdit[index]['expandedKeys']"
              v-model:checkedKeys="checkedKeys['c'+index]"
              v-model:selectedKeys="treeEdit[index]['selectedKeys']"
              class="u-commit-audit-tree"
              v-if="refresh"
              @check="treeCheck"
              @select="treeSelect">
            </Tree>
          </CollapsePanel>
        </Collapse>
      </CollapsedSider>
      <UTableContent ref="tabContentRef">
        <UTable
          :columns="columns"
          :data="tabData"
          v-bind="tableProps"
          :scroll="{ y: 'calc(100vh - 230px)' }"></UTable>
      </UTableContent>
    </Layout>
    <template #footerBefore></template>
  </UDialog>
</template>

<script lang="ts" setup>
defineOptions({
  name: "u-sel-roleuser-copy",
});
import { ref, reactive, useAttrs, watch, onMounted, h, computed, nextTick, isRef } from "vue";
import { _IFormEl, _IExtra } from "@/src/components/common/form/interface";
import { _IColumnProps } from "@/components/common/tableEdit/interface.ts";
import { storeToRefs } from "pinia";
import { useLoginStore, useBaseStore } from "@/store";
import { Button, Popconfirm, TableColumnProps, Tree, Layout, Collapse, CollapsePanel, Checkbox, Modal, CheckboxGroup } from "ant-design-vue";
import { cloneDeep } from "lodash";
import UIconFont from "@/components/common/iconfont/IconFont.vue";
import { nullC } from "@/util/common";
import { getItemByIds, debounce, throttle, groupBy1 } from "@/util/format.ts"
import UDialog from '@/components/common/dialog/DialogM.vue'
import CollapsedSider from './../sider/Sider.vue'
import UTree from './../tree/Tree.vue'
import UTableContent from './../content/TableContent.vue'
import UTable from './../table/Table.vue'
import * as userApi from "@/service/system/user";

const props = withDefaults(
  defineProps<{
    selData: string | string[];
    isLoadData: boolean;
    treeProps: object;
    tableProps: object;
    filterParent: boolean;
    multiple: boolean;
    checkStrictly: boolean;
    parent: objetc;
  }>(),
  {
    selData: [], // 已选中的数据
    treeProps: {}, // 树形参数
    tableProps: {}, // 列表参数
    isLoadData: true, // 是否加载初始数据
    filterParent: true, // 结果是否过滤掉父级
    multiple: true, // 是否多选
    checkStrictly: false, // 父子是否强关联
    parent: {
      key: "deptname",
      valueKey: "fkparentid",
      parentTLable: "所属角色",
    },
  }
);

const attrs = useAttrs();

let activeKey = ref("0");

const treeEdit = ref<{ [key: string]: object }>({});
const checkedKeys = ref<{ [key: string]: object }>({});
const parentCheckes = ref<{ [key: string]: any[] }>({});

const emits = defineEmits(["submit", "change"]);

const { userInfo } = storeToRefs(useLoginStore());
const { deptUsers, deptData } = storeToRefs(useBaseStore());
const formLoading = ref<boolean>(false);

// 初始化表格
const tabData = ref<any[]>([]);
let columns: Array<TableColumnProps> = reactive([
  {
    dataIndex: "index",
    title: "序号",
    align: "center",
    width: 100,
    customRender: ({ index }) => (index += 1),
  },
  // { dataIndex: props.parent.key, title: props.parent.parentTLable, align: "center" },
  { dataIndex: "name", title: "姓名" },
  {
    dataIndex: "remove",
    title: "操作",
    width: 100,
    align: "center",
    customRender: ({ record, text, index }) => {
      return h(UIconFont, {
        type: "icon-a-shanchu1",
        style: { color: "#1890ff" },
        onClick: () => {
          tabData.value.splice(index, 1);
          props.multiple == true ? checkedKeys.value.splice(index, 1) : selectedKeys.value.splice(index, 1);
          refreshTree();
        },
      });
    },
  },
]);

// 获取角色人员数据
const refresh = ref<boolean>(true);
const getExtraData = computed(() => {
  let tExData = cloneDeep(attrs["extraData"] || []);
  return isRef(tExData) ? tExData.value : tExData;
});

const roleUserData = ref([]);
const treeData = computed(() => {
  let tExData = attrs["extraData"] || [];
  return [...getExtraData.value, ...(props.isLoadData == true ? roleUserData.value : [])];
});
const parentIds = computed(() => {
  if (props.isLoadData == true) {
    return (deptData.value || []).map((i) => i.keyid);
  } else {
    return getExtraData.value.map((i) => i.keyid);
  }
});

// 设置父级节点选择器
const setParentKey = () => {
  let tParents = {};
  for(let i = 0; i <= 10; i++) {
    parentCheckes['parent'+i] = reactive([])
    checkedKeys.value['c'+i] = []
    treeEdit.value[i] = reactive({
      checkedKeys: reactive([]),
      expandedKeys: reactive([]),
      selectedKeys: reactive([]),
    });
  }
}

// 获取角色人员信息数据
function getRoles() {
  userApi.roleuserselectdata().then((res) => {
    if (res.code == 0) {
      let tdata = res.data || [];
      setTimeout(() => {
        roleUserData.value = tdata;
        echoInfo();
      }, 100);
    }
  });
}

// 父级选中事件
function parentChange(e, item, index) {
  checkedKeys.value['c0'] = [1,2,3,4,5]
  return
  let tItem = cloneDeep(item);
  delete tItem["children"];

  let treeIndexChecks = treeEdit.value[index].checkedKeys

  let chData = [tItem, ...(item.children || [])];
  if (e.length != 0) {
    // 父子强关联
    if (props.checkStrictly == false) {
      chData.forEach((child) => {
        treeIndexChecks.push(child.keyid)
        treeCheck([], { checked: true, node: child });
      });
    } else {
      treeCheck([], { checked: true, node: tItem });
    }
  } else {
    if (props.checkStrictly == false) {
      chData.forEach((child) => {
        treeIndexChecks = treeIndexChecks.filter(keyid => keyid != child.keyid)
        treeCheck([], { checked: false, node: child });
      });
    } else {
      treeCheck([], { checked: false, node: tItem });
    }
  }
  
  // treeEdit[index].value.checkedKeys.splice(0, treeEdit[index].checkedKeys.length, ...treeIndexChecks)
  treeEdit.value[index] = {
    checkedKeys: ['aaaa']
  }
}

// 树形属性勾选事件
function treeCheck(keys, { checked, checkedNodes, node, event }) {
  if (checked == true) {
    tabData.value.push(node);
  } else {
    let index = cloneDeep(tabData.value).findIndex((i) => i.keyid == node.keyid);
    if (index != -1) {
      tabData.value.splice(index, 1);
    }
  }
}

// 属性点击事件
function treeSelect(selectedKeys, { selected, selectedNodes, node, event }) {
  if (props.multiple == true) return;
  tabData.value = selectedNodes;
}

// 确认提交
const submit = () => {
  let tData = cloneDeep(tabData.value);
  if (props.filterParent == true) {
    tData = tData.filter((o) => !parentIds.value.includes(o.keyid));
  }
  emits("submit", cloneDeep(tabData.value));
  emits("change", cloneDeep(tabData.value));

  dialogClose();
};

// 回显选中的数据
const echoInfo = () => {
  let tSelData = cloneDeep(props.selData);
  if (typeof tSelData == "string") {
    tSelData = tSelData.split(",");
  }
  let tTabData = cloneDeep(getItemByIds(treeData.value, Array.from(new Set(tSelData))));

  // 选中树形子级
  const parentGroup = groupBy1(tTabData, "fkparentid", false);
  for (let key in parentGroup) {
    if (key == 0 && props.filterParent == true) {
      parentGroup[key].forEach((o) => {
        let index = treeData.value.findIndex((i) => i.keyid == o.keyid);
        if (props.multiple == true) {
          treeEdit.value[index]["checkedKeys"].push(o.keyid);
        } else {
          treeEdit.value[index]["selectedKeys"] = o.keyid;
        }
      });
    }
    if (key != 0) {
      let index = treeData.value.findIndex((i) => i.keyid == key);
      if (props.multiple == true) {
        treeEdit.value[index]["checkedKeys"].push(parentGroup[key].map((o) => o.keyid).join());
      } else {
        treeEdit.value[index]["selectedKeys"] = parentGroup[key].map((o) => o.keyid);
      }
    }
  }

  // 渲染列表
  tTabData.forEach((i) => {
    delete i["children"];
  });
  tTabData.forEach((item) => {
    if (!tabData.value.some((i) => i.keyid == item.keyid)) {
      tabData.value.push(item);
    }
  });
};

// 父级选择框的点击事件
const checkedClick = (event) => {
  event.stopPropagation();
};

// 刷新树
let timer = null;
const refreshTree = () => {
  refresh.value = false;
  nextTick(() => {
    refresh.value = true;
  });
};

watch(
  () => attrs.open,
  (nval, oval) => {
    if (nval == true) {
      setParentKey()
      getRoles();
    }
  },
  { immediate: true, deep: true }
);

// 弹窗关闭
const dialogClose = () => {
  treeEdit.value = {};
  tabData.value = [];
};
</script>

<style lang="scss">
.u-role-user-collapse {
  .ant-collapse-header {
    padding: 0 16px !important;
  }

  .ant-collapse-content-box {
    padding-block: 0 !important;
  }
}
</style>
